package com.czy.seed.mvc.home.controller;

import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.controller.BaseController;
import com.czy.seed.mvc.home.entity.*;
import com.czy.seed.mvc.home.service.*;
import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.service.SysRoleService;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.ExportExcel;
import com.czy.seed.mvc.util.MailUtil;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.Res;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author pc
 * @Author: liuyun
 * Created by liuyun  10:04 2017/11/23.
 */


@RestController
@RequestMapping("/home/order")
public class OrderController extends BaseController<Orders> {

    public static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private PurchaseOrdersService purchaseOrdersService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private MenuService menuServic;

    @Autowired
    private PurchaseDetailedListService purchaseDetailedListService;

    /**
     * 统计采购单位在某一时间段内采购的情况
     * liuyun
     *
     * @return
     */
    @RequestMapping("/unitTimeStatistics")
    public Res unitTimeStatistics(String userId, Date startTime, Date overTime, int type) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            String start = formatter.format(startTime);
            String over = formatter.format(overTime);
            QueryParams queryParamss = new QueryParams(Menu.class);
            QueryParams.Criteria criterias = queryParamss.createCriteria();
            criterias.andEqualTo("menuGrade", 1);
            List<Menu> menuList = menuServic.selectListByParams(queryParamss);
            List<String> ff = JSONObject.parseObject(userId, List.class);
            QueryParams queryParams = new QueryParams(PurchaseOrders.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            switch (type) {
                case 0:
                    String jieguo = userId.substring(userId.indexOf("[") + 1, userId.indexOf("]")).replaceAll("\"", "");
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.MERCHANTID in (" + jieguo + ") ");
                    break;
                case 1:
                    criteria.andIn("creator_userid", ff);
                    break;
                case 2:
                    ff = new ArrayList<>();
                    ff.add(PrincipalUtil.getLoginUser().getId().toString());
                    criteria.andEqualTo("creator_userid", PrincipalUtil.getLoginUser().getId());
                    String jie = userId.substring(userId.indexOf("[") + 1, userId.indexOf("]")).replaceAll("\"", "");
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.GOODS_TYPE in (" + jie + ") ");
                    break;
                case 3:
                    QueryParams queryParamssp = new QueryParams(Merchant.class);
                    QueryParams.Criteria criteriass = queryParamssp.createCriteria();
                    criteriass.andEqualTo("userId",PrincipalUtil.getLoginUser().getId());
                    List<Merchant> merchants = merchantService.selectListByParams(queryParamssp);
                    ff = new ArrayList<>();
                    ff.add(merchants.get(0).getId()+"");
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.MERCHANTID = " + merchants.get(0).getId());
                    String jieg = userId.substring(userId.indexOf("[") + 1, userId.indexOf("]")).replaceAll("\"", "");
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.GOODS_TYPE in (" + jieg + ") ");
                    break;
                default:
            }


            criteria.andCondition(" PURCHASEDETAILEDLISTLIST.TYPE = '已完成' and PURCHASEDETAILEDLISTLIST.UPDATETIME > '" + start + "' and PURCHASEDETAILEDLISTLIST.UPDATETIME < '" + over + "'");

            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectListRelativeByParams(queryParams);
            List<Object> objects = new ArrayList<>();
            //所有商品类型
            String[] uu = new String[0];

            for (String f : ff) {
                Map<String, Object> page = new HashMap<String, Object>();
                List<PurchaseDetailedList> purchaseDetailedList = new ArrayList<>();
                for (PurchaseOrders purchaseOrder : purchaseOrders) {
                    if (type == 1 || type == 2) {
                        if (Long.parseLong(f) == purchaseOrder.getCreator_userid()) {
                            for (int i = 0; i < purchaseOrder.getPurchaseDetailedListList().size(); i++) {
                                for (Menu menu : menuList) {
                                    if (Long.parseLong(purchaseOrder.getPurchaseDetailedListList().get(i).getGoodsType()) == menu.getId()) {
                                        purchaseOrder.getPurchaseDetailedListList().get(i).setGoodsType(menu.getName());
                                        break;
                                    }

                                }
                                purchaseDetailedList.add(purchaseOrder.getPurchaseDetailedListList().get(i));
                            }
                        }
                    }

                    if (type == 0 || type == 3) {
                        for (int i = 0; i < purchaseOrder.getPurchaseDetailedListList().size(); i++) {
                            if (purchaseOrder.getPurchaseDetailedListList().get(i).getMerchantid() == Long.parseLong(f)) {
                                for (Menu menu : menuList) {
                                    if (Long.parseLong(purchaseOrder.getPurchaseDetailedListList().get(i).getGoodsType()) == menu.getId()) {
                                        purchaseOrder.getPurchaseDetailedListList().get(i).setGoodsType(menu.getName());
                                        break;
                                    }

                                }
                                purchaseDetailedList.add(purchaseOrder.getPurchaseDetailedListList().get(i));
                            }
                        }

                    }

                }
                //对每一个用户针对每一种商品分组
                Map<String, List<PurchaseDetailedList>> group = purchaseDetailedList.stream().collect(Collectors.groupingBy(PurchaseDetailedList::getGoodsType));

                ArrayList<Object> objects1 = new ArrayList<>();
                for (String key : group.keySet()) {
                    HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("name", key);
                    objectObjectHashMap.put("val", group.get(key));
                    objects1.add(objectObjectHashMap);
                }

                Object[] keySet = group.keySet().toArray();
                //获取所有集合中商品类型的总类，重复的去重，多余的新增，并且从小到大排好序
                uu = Stream.concat(Stream.of(uu), Stream.of(keySet)).distinct().sorted().toArray(String[]::new);
                if (type == 3) {
                    page.put("name", PrincipalUtil.getLoginUser().getId());
                } else {
                    page.put("name", f);
                }

                page.put("val", objects1);
                objects.add(page);
            }

            pageInfo.put("goodsType", uu);
            pageInfo.put("objectsList", objects);
            pageInfo.put("userName", PrincipalUtil.getLoginUser());

            logger.info("图表数据生成成功！");
        } catch (Exception e) {
            logger.error("图表数据生成失败 ", e);
        }
        return Res.ok(pageInfo);
    }

    /**
     * 查询当前用户所属采购单位的信息
     * liuyun
     *
     * @return
     */
    @RequestMapping("/presentUser")
    public Res presentUser() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            QueryParams queryParams = new QueryParams(Menu.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("menuGrade", 1);
            List<Menu> menus = menuServic.selectListByParams(queryParams);
            List<SysUser> unit = sysUserService.presentUser(PrincipalUtil.getLoginUser().getId(), "unit");
            List<SysUser> userList = sysUserService.presentUser(PrincipalUtil.getLoginUser().getId(), "finalist");
            List<Long> userId = new ArrayList();
            for(SysUser user:userList){
                userId.add(user.getId());

            }
            QueryParams queryParam = new QueryParams(Merchant.class);
            QueryParams.Criteria criterias = queryParam.createCriteria();
            List<Merchant> merchants = new ArrayList<>();
            if(userId.size()>0){
                criterias.andIn("userId",userId);
                merchants = merchantService.selectListByParams(queryParam);
            }


            pageInfo.put("unit", unit);
            pageInfo.put("goodsType", menus);
            pageInfo.put("unit", unit);
            pageInfo.put("merchant", merchants);
            logger.info("采购办{}，当前用户所属采购单位信息查询成功！", PrincipalUtil.getLoginUser().getName());
        } catch (Exception e) {
            logger.error("采购办{}，当前用户所属采购单位信息查询失败！", PrincipalUtil.getLoginUser().getName(), e);
            return Res.error();
        }
        return Res.ok(pageInfo);
    }


    /**
     * 下载采购单位数据统计EXCEL表格
     * liuyun
     *
     * @return
     */
    @RequestMapping("/unitDownLoadExcel")
    public void unitDownLoadExcel(String userId, Date startTime, Date overTime, int type, HttpServletResponse response) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            String start = formatter.format(startTime);
            String over = formatter.format(overTime);
            List<Long> ff = Arrays.asList(userId.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            QueryParams queryParams = new QueryParams(PurchaseOrders.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            switch (type) {
                case 0:
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.MERCHANTID in (" + userId + ") ");
                    break;
                case 1:
                    criteria.andIn("creator_userid", ff);
                    break;
                case 2:
                    criteria.andEqualTo("creator_userid", PrincipalUtil.getLoginUser().getId());
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.GOODS_TYPE in (" + userId + ") ");
                    break;
                case 3:
                    QueryParams queryParamssp = new QueryParams(Merchant.class);
                    QueryParams.Criteria criteriass = queryParamssp.createCriteria();
                    criteriass.andEqualTo("userId",PrincipalUtil.getLoginUser().getId());
                    List<Merchant> merchants = merchantService.selectListByParams(queryParamssp);
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.MERCHANTID = " + merchants.get(0).getId());
                    criteria.andCondition(" PURCHASEDETAILEDLISTLIST.GOODS_TYPE in (" + userId + ") ");
                    break;
                default:
            }
            criteria.andCondition(" PURCHASEDETAILEDLISTLIST.TYPE = '已完成' and PURCHASEDETAILEDLISTLIST.UPDATETIME > '" + start + "' and PURCHASEDETAILEDLISTLIST.UPDATETIME < '" + over + "'");

            List<PurchaseOrders> purchaseOrders = purchaseOrdersService.selectListRelativeByParams(queryParams);
            List<ExcelStatisticsVo> excelStatisticsVoList = convertObject(purchaseOrders);
            ExportExcel.exportExcel(excelStatisticsVoList, "政府采购协议供货和定点采购项目情况报表", "报表", ExcelStatisticsVo.class, "政府采购协议供货和定点采购项目情况报表.xls", response);
        } catch (Exception e) {

            logger.error("导出EXCEL表格数据异常{}", e);
        }

    }

    /**
     * 平台数据统计分析
     * liuyun
     */
    @RequestMapping("/statisticsData")
    public Res statisticsData() {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try{
            QueryParams queryParamss = new QueryParams(Menu.class);
            QueryParams.Criteria criterias = queryParamss.createCriteria();
            criterias.andEqualTo("menuGrade", 1);
            List<Menu> menuList = menuServic.selectListByParams(queryParamss);
            List<StatisticsDataVo> statisticsDataVos = purchaseDetailedListService.statisticsData();
            for (int i = 0; i < statisticsDataVos.size(); i++) {
                for (Menu menu : menuList) {
                    if (Long.parseLong(statisticsDataVos.get(i).getGoodsType()) == menu.getId()) {
                        statisticsDataVos.get(i).setGoodsType(menu.getName());
                        break;
                    }
                }
            }
            HashMap<Object, Object> objectObjectHashMap1 = new HashMap<>();
            Map<String, List<StatisticsDataVo>> typeGroup = statisticsDataVos.stream().collect(Collectors.groupingBy(StatisticsDataVo::getGoodsType));
            typeGroup.forEach((k, v) -> {
                HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("totalMoney",v.stream().map(StatisticsDataVo::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
                objectObjectHashMap.put("bazaarMoney",v.stream().map(StatisticsDataVo::getMAK_PRC).reduce(BigDecimal.ZERO, BigDecimal::add));
                objectObjectHashMap1.put(k,objectObjectHashMap);
            });
            BigDecimal totalMoney = statisticsDataVos.stream().map(StatisticsDataVo::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal bazaarMoney =  statisticsDataVos.stream().map(StatisticsDataVo::getMAK_PRC).reduce(BigDecimal.ZERO, BigDecimal::add);

            pageInfo.put("statisticsData",objectObjectHashMap1);
            pageInfo.put("totalMoney",totalMoney);
            pageInfo.put("bazaarMoney",bazaarMoney);
        }catch (Exception e){
            logger.error("平台数据统计分析异常！{}",e);
            return Res.error();
        }

        return Res.ok(pageInfo);

    }


    /**
     * 转换EXCEL实体对象所用的工具类
     *
     * @param purchaseOrders liuiyun
     * @return
     */
    public List<ExcelStatisticsVo> convertObject(List<PurchaseOrders> purchaseOrders) {
        List<ExcelStatisticsVo> excelStatisticsVos = new ArrayList<>();
        try {
            for (PurchaseOrders purchaseOrder : purchaseOrders) {
                for (PurchaseDetailedList purchaseDetailedList : purchaseOrder.getPurchaseDetailedListList()) {

                    Commodity commodity = commodityService.selectByPrimaryKey(purchaseDetailedList.getCommodityId());
                    if (commodity == null) {
                        commodity = new Commodity();
                        commodity.setModel("");
                        commodity.setCommodityTrcPrc(new BigDecimal(0));
                        commodity.setCommodityMakPrc(new BigDecimal(0));
                        commodity.setUnit("件");
                    }
                    Merchant merchant = merchantService.selectByPrimaryKey(purchaseDetailedList.getMerchantid());
                    if (merchant == null) {
                        merchant = new Merchant();
                        merchant.setCompanyName("");
                        merchant.setTel("");

                    }
                    ExcelStatisticsVo excelStatisticsVo = new ExcelStatisticsVo("", purchaseDetailedList.getPmbm(), purchaseDetailedList.getPmmc(),
                            commodity.getModel(), purchaseDetailedList.getGgxh(), commodity.getCommodityMakPrc().toString(),
                            commodity.getCommodityTrcPrc().toString(), purchaseDetailedList.getFinalPrice() + "", purchaseDetailedList.getSl().toString() + commodity.getUnit(),
                            purchaseDetailedList.getZj() + "", purchaseDetailedList.getUpdatetime(),
                            purchaseOrder.getCompany_name(), merchant.getCompanyName(), merchant.getTel());
                    excelStatisticsVos.add(excelStatisticsVo);
                }
                for (int i = 0; i < excelStatisticsVos.size(); i++) {
                    excelStatisticsVos.get(i).setNum(i + 1 + "");

                }

            }
        } catch (Exception e) {
            logger.error("导出EXCEL表格数据装换异常{}", e);

        }
        return excelStatisticsVos;
    }


}
